package com.kma.summer2012.client.presenters.manager;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.Widget;
import com.kma.summer2012.client.CrumbsEventBus;
import com.kma.summer2012.client.events.manager.ManageWorksEvent;
import com.kma.summer2012.client.presenters.Presenter;
import com.kma.summer2012.client.services.AbstractCallBack;
import com.kma.summer2012.client.services.catalogOfWorks.CrumbsCatalogOfWorksService;
import com.kma.summer2012.client.services.session.CrumbsSessionService;
import com.kma.summer2012.shared.model.UICrumbsWorkItem;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class AddWorkCategoryPresenter implements Presenter {

    public interface Display {
        public HasClickHandlers getSaveButton();

        public HasClickHandlers getCancelButton();

        public void setName(String name);

        public String getName();

        public void setDescription(String description);

        public String getDescription();

        public void setCategoryList(Map<Integer, String> list);

        public void setSelectedParent(int category);

        public int getSelectedParent();

        Widget asWidget();

    }

    private final Display display;
    private UICrumbsWorkItem item;
    final Map<Integer, String> categoryList = new HashMap<Integer, String>();

    public AddWorkCategoryPresenter(Display display) {
        this.display = display;
        bind();
        CrumbsSessionService.App.getInstance().getParameterWorkItem("editCategory", new AbstractCallBack<UICrumbsWorkItem>() {
            @Override
            public void onSuccess(UICrumbsWorkItem uiCrumbsWorkItem) {
                item = uiCrumbsWorkItem;
                setParameters();
            }
        });

    }

    private void bind() {
        this.display.getSaveButton().addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent clickEvent) {
                doSaveWork();
            }
        });
        this.display.getCancelButton().addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent clickEvent) {
                CrumbsEventBus.getInstance().fireEvent(new ManageWorksEvent());
            }
        });
    }

    private void doSaveWork() {
        if (!this.display.getName().equals("") && !this.display.getDescription().equals("")) {
            this.item.setWorkName(this.display.getName());
            this.item.setWorkDescription(this.display.getDescription());
            this.item.setParent(true);
            final int parent = item.getParentId();
            if (this.display.getSelectedParent() == 0) {
                this.item.setParentId(0);
            }
            CrumbsCatalogOfWorksService.App.getInstance().getAllWorks(new AbstractCallBack<Set<UICrumbsWorkItem>>() {
                @Override
                public void onSuccess(Set<UICrumbsWorkItem> uiCrumbsWorkItems) {

                    boolean add = true;
                    for (UICrumbsWorkItem item : uiCrumbsWorkItems) {
                        if (item.getWorkName().equals(AddWorkCategoryPresenter.this.display.getName()) && !item.isDelete() && item.getId() != AddWorkCategoryPresenter.this.item.getId()) {
                            add = false;
                        }
                        if (item.getWorkName() == AddWorkCategoryPresenter.this.categoryList.get(AddWorkCategoryPresenter.this.display.getSelectedParent())) {
                            AddWorkCategoryPresenter.this.item.setParentId(item.getId());
                        }
                    }
                    if (add) {
                        CrumbsCatalogOfWorksService.App.getInstance().saveWorkItem(item, new AbstractCallBack<Void>() {
                            @Override
                            public void onSuccess(Void aVoid) {
                                CrumbsCatalogOfWorksService.App.getInstance().checkForSubcategory(item.getParentId(), item, new AbstractCallBack<Boolean>() {
                                     @Override
                                    public void onSuccess(Boolean aBoolean) {
                                        if (aBoolean && (item.getParentId() != 0 && item.getId() != 0)) {
                                            CrumbsCatalogOfWorksService.App.getInstance().getWorkById(item.getParentId(), new AbstractCallBack<UICrumbsWorkItem>() {
                                                @Override
                                                public void onSuccess(UICrumbsWorkItem uiCrumbsWorkItem) {
                                                    uiCrumbsWorkItem.setParentId(parent);
                                                    CrumbsCatalogOfWorksService.App.getInstance().saveWorkItem(uiCrumbsWorkItem, new AbstractCallBack<Void>() {
                                                        @Override
                                                        public void onSuccess(Void aVoid) {
                                                            AddWorkCategoryPresenter.this.display.setName("");
                                                            AddWorkCategoryPresenter.this.display.setDescription("");
                                                            AddWorkCategoryPresenter.this.display.setCategoryList(new HashMap<Integer, String>());
                                                            CrumbsEventBus.getInstance().fireEvent(new ManageWorksEvent());
                                                        }
                                                    });

                                                }
                                            });
                                        } else {
                                            AddWorkCategoryPresenter.this.display.setName("");
                                            AddWorkCategoryPresenter.this.display.setDescription("");
                                            AddWorkCategoryPresenter.this.display.setCategoryList(new HashMap<Integer, String>());
                                            CrumbsEventBus.getInstance().fireEvent(new ManageWorksEvent());
                                        }
                                    }
                                });

                            }
                        });
                    } else {
                        Window.alert("Category with such name already exists, please enter another name");
                    }
                }
            });


        } else {
            Window.alert("Not all data is inserted");
        }

    }

    private void setParameters() {

        CrumbsCatalogOfWorksService.App.getInstance().getAllCategories(new AbstractCallBack<List<String>>() {
            @Override
            public void onSuccess(List<String> strings) {

                int j = 1;
                if (item.getWorkName() != null) {
                    for (String string : strings) {
                        if (!item.getWorkName().equals(string)) {
                            categoryList.put(j, string);
                            j++;
                        }
                    }
                } else {
                    for (String string : strings) {
                        categoryList.put(j, string);
                        j++;
                    }

                }
                display.setCategoryList(categoryList);
                try {
                    if (item.getId() != 0) {
                        display.setName(AddWorkCategoryPresenter.this.item.getWorkName());
                        display.setDescription(AddWorkCategoryPresenter.this.item.getWorkDescription());
                        if (item.getParentId() != 0) {


                            CrumbsCatalogOfWorksService.App.getInstance().getWorkById(AddWorkCategoryPresenter.this.item.getParentId(), new AbstractCallBack<UICrumbsWorkItem>() {
                                @Override
                                public void onSuccess(UICrumbsWorkItem uiCrumbsWorkItem) {
                                    for (int key : categoryList.keySet()) {
                                        if (categoryList.get(key) == uiCrumbsWorkItem.getWorkName()) {
                                            display.setSelectedParent(key);
                                        }
                                    }

                                }
                            });
                        }
                    }
                    //else display.setPageTitle("Add work");
                } catch (Exception e) {
                    e.printStackTrace();
                    Window.alert("EditWorkCategory Presenter can't open received workItem");
                }
            }
        });

    }

    @Override
    public void go(HasWidgets container) {
        container.clear();
        container.add(display.asWidget());
    }
}
